package com.wing.oauth2.listener;

import com.wing.oauth2.details.userdetails.user.SysUserDetails;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;

/**
 * 认证成功监听器
 *
 * @author
 */
@Component
public class AuthenticationSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {

    // @Autowired
    // private UserClient userClient;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        if(event.getSource() instanceof UsernamePasswordAuthenticationToken){
            UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) event.getSource();
            if(token != null && token.getPrincipal() instanceof SysUserDetails){
                //在这里做登录日志
                System.out.println("+++++++登录成功监听器被调用+++++++");
                // HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                //
                // OperationLog log = new OperationLog();
                //
                // //获取登录用户
                // log.setCreator(((UserDetailImpl) token.getPrincipal()).getId());
                // log.setCreatorName(((UserDetailImpl) token.getPrincipal()).getUsername());
                // //日志标题
                // log.setName("登录成功");
                // //日志类型
                // log.setType(OperationLog.Type.login);
                // //日志请求url
                // log.setRequestUrl(request.getRequestURI());
                // //请求方式
                // log.setRequestType(request.getMethod());
                // //请求参数
                // log.setRequestParam(HttpServletRequestUtils.getRequestParams(request).toJSONString());
                // //IP信息
                // String ip = HttpServletRequestUtils.getIpAddr(request);
                // log.setIp(ip);
                // String[] ipArray = ip.split(",");
                // String ipInfo = "";
                // if(ipArray.length > 0){
                //     for (int i = 0; i < ipArray.length; i++) {
                //         ipArray[i] = ipArray[i].replace(" ","");
                //         String mainInfo = SystemLogAspect.qqWry.findIP(ipArray[i]).getMainInfo();
                //         ipInfo += i > 0 ? "," + mainInfo : mainInfo;
                //     }
                // }
                // log.setIpInfo(ipInfo);
                // userClient.addOperationLog(log);
            }
        }
    }
}
